package com.dzirtbry.miner.model;

import java.awt.*;
import java.util.logging.Logger;

/**
 * User: dzirtbry
 * Date: 2/26/12
 * Time: 3:58 PM
 */
public class Pane {
    private static final Logger logger = Logger.getLogger(Pane.class.getName());

    private Cell[][] pane;
    private int mines;

    private Pane() {
    }

    /**
     * Returns instance of Pane
     *
     * @param d     Dimesion of the field
     * @param mines number of mines in the field
     * @param row   row of the first click
     * @param col   col of the first click
     * @return Created pane
     */
    public static Pane generatePane(Dimension d, int mines, int row, int col) {
        logger.finest("Attempt to create pane with dimsion " + d + "and " + mines + "mines");
        if (mines >= d.height * d.width) {
            throw new IllegalArgumentException("Too much mines");
        }
        Pane p = new Pane();
        p.mines = mines;
        p.pane = new Cell[d.height][d.width];
        int putted = 0;
        while (putted < mines) {
            int r = (int) (Math.random() * d.height);
            int c = (int) (Math.random() * d.width);
            if (r == row && c == col) {
                continue;
            }
            if (!p.getCell(r, c).isMined()) {
                p.getCell(r, c).setMined(true);
                if (r>0) {
                    p.getCell(r-1,c).incNumber();
                    if (c>0) {
                        p.getCell(r-1,c-1).incNumber();
                    }
                    if (c<d.width-1) {
                        p.getCell(r-1,c+1).incNumber();
                    }
                }
                if (r<d.height-1) {
                    p.getCell(r+1,c).incNumber();
                    if (c>0) {
                        p.getCell(r+1,c-1).incNumber();
                    }
                    if (c<d.width-1) {
                        p.getCell(r+1,c+1).incNumber();
                    }
                }
                if (c>0) {
                    p.getCell(r,c-1).incNumber();
                }
                if (c<d.width-1) {
                    p.getCell(r,c+1).incNumber();
                }
                putted++;
            }
        }
        logger.finest("Pane successfully created");
        return p;
    }

    /**
     * Returns cell at specified position
     *
     * @param row number
     * @param col number
     * @return Cell is specified row and col
     */
    public Cell getCell(int row, int col) {
        return pane[row][col];
    }

    /**
     * Get number of mines in the field
     *
     * @return number of mines
     */
    public int getMines() {
        return mines;
    }

}
